/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package examplesocket;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.util.Collections;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author 5m
 */
public class Server extends Thread{
    ServerSocket server;
    ServerAccept mySa;
    ConcurrentHashMap<String, Stream> listaClient;
    Boolean stillRunning;
    Vector<User> registeredUsers;
    Server(int porta)
    {
        try
        {
            server = new ServerSocket(porta);
            server.setSoTimeout(1000);
        }
        catch(IOException e)
        {
            System.err.println("Error while opening port :'(");
        }
        stillRunning=true;
    }
    
    void serviceStarter()
    {
        registeredUsers = new Vector();
        listaClient = new ConcurrentHashMap();
        try{
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("registeredUsers"));
        registeredUsers = (Vector<User>) ois.readObject();
        ois.close();
        } catch (Exception e) {}
        System.out.println("Vector length: " + registeredUsers.size());
        mySa = new ServerAccept(server,listaClient,registeredUsers);
        mySa.start();
    }
    
    void serviceStopper()
    {
          try {
          ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("registeredUsers"));
          oos.writeObject(registeredUsers);
          oos.close();
          } catch(IOException e) {}
          mySa.serviceStop();
    }
    
    @Override
    public void run()
    {
       serviceStarter();
    }
}
